/*
 * Copyright 2011 Michele Mancioppi [michele.mancioppi@gmail.com]
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package cave.nice.testMessage.cron;

import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cave.nice.testMessage.TestMessageConstants;
import cave.nice.testMessage.data.CannotRetrieveEntitiesException;
import cave.nice.testMessage.data.DataManager;
import cave.nice.testMessage.data.VerifiedAccount;

import com.google.appengine.api.taskqueue.Queue;
import com.google.appengine.api.taskqueue.QueueFactory;
import com.google.appengine.api.taskqueue.TaskOptions;

@SuppressWarnings("serial")
public class GenerateTestsServlet extends HttpServlet {

	private final Queue tasksQueue = QueueFactory
			.getQueue(TestMessageConstants.REPORTING_TASKS_QUEUE_NAME);

	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException {
		DataManager dataStoreManager = DataManager.getInstance();

		try {
			/*
			 * Perform test of the email. It generates an email and sends it to
			 * the specified address specified. The email contains a timestamp,
			 * that is kept by the servlet using a database and it is checked by
			 * the CheckMessageServlet
			 */
			List<VerifiedAccount> accounts = dataStoreManager
					.getVerifiedAccounts();
			for (VerifiedAccount account : accounts) {
				/*
				 * TODO Add task names
				 */
				tasksQueue.add(TaskOptions.Builder
						.withUrl("/resources/accounts/"
								+ account.getEmailAddress() + "/tests"));
			}
		} catch (CannotRetrieveEntitiesException e) {
			throw new ServletException(e);
		} finally {
			dataStoreManager.close();
		}
	}

}
